package servlet;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import utils.DBUtil;
import utils.DBUtil_Plus;

import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;

@WebServlet("/group/equipment/Equipment_delete")
public class EquipmentDelete extends HttpServlet {
    private static final long serialVersionUID = 1L;
    public EquipmentDelete(){
        super();
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html; charset=UTF-8");
        String id = req.getParameter("id");
        if (id != null && !id.trim().isEmpty()) {
            int delete_id = Integer.parseInt(id);
            Connection conn = null;
            try {
//                conn = DBUtil_Plus.getConnection();
                conn = DBUtil.getConnection();
            // 获取执行sql的对象Statement
            Statement stmt = conn.createStatement();
            String sql = "delete from eq_list where id = " + delete_id + " ";
            int rs = stmt.executeUpdate(sql);
            // UPDATE eq_list SET id = id - 1 WHERE id > 1;
            // 创建一条数据操纵语句，如 UPDATE 或 DELETE
            String sql1 = "UPDATE eq_list set id =  id - 1 where id > " + delete_id + " ";
            stmt.executeUpdate(sql1);
            DBUtil_Plus.closeConnection(conn);
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        } else {

        }
        resp.setHeader("refresh", "0;URL=" + "Equipment_list");
    }
}
